<template>
  <div class="box-content">
    <div class="canvas-wrapper" v-for="(pdf, index) in pagesCount" :key="index">
      <canvas
        class="annotation-canvas"
        :id="`annotation-canvas_${index}`"
        :data-index="index"
      ></canvas>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref } from "vue";
import { PDFDocument } from "pdf-lib";
import * as pdfjsLib from "pdfjs-dist";
pdfjsLib.GlobalWorkerOptions.workerSrc =
  "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js";
let pdfDoc: any = null;
const pdfUrl = ref<string>("");
const pagesCount = ref<number>(0);
const useRederPdf = async () => {
  /**
   * @description: 获取pdfUrl
   * @param {string} url
   * @return {*}
   */
  const existingPdfBytes = await fetch("file/vuejs.pdf").then((res) =>
    res.arrayBuffer()
  );
  pdfDoc = await PDFDocument.load(existingPdfBytes);
  const pdfBytes = await pdfDoc.save();
  const blob = new Blob([pdfBytes], { type: "application/pdf" });
  pdfUrl.value = URL.createObjectURL(blob);

  console.log(pdfUrl.value, "pdfUrl.value");
  /**
   * @description: 渲染pdf与pdf-lib
   * @param {number} scale // 放大倍数
   * @param {boolean} istThumbnail // 是否产生缩略图
   * @return {*}
   */
  let scale = 1;
  if (!pdfUrl.value) return;
  const loadingTask = pdfjsLib.getDocument(pdfUrl.value);

  const pdf = await loadingTask.promise;
  const thumbnailArr: string[] = []; // 缩略图
  const thumbnailInfoArr: { imgUrl: string; pageIndex: number }[] = [];
  pagesCount.value = pdf.numPages;

  for (let i = 1; i <= pagesCount.value; i++) {
    const page = await pdf.getPage(i);
    // 使用调整后的缩放比例创建视口
    const viewport = page.getViewport({ scale: 1 });

    // 获取对应页面的DOM canvas元素
    const canvasElement = document.getElementById(
      `annotation-canvas_${i - 1}`
    ) as HTMLCanvasElement;
    if (canvasElement) {
      // 设置canvas尺寸
      canvasElement.width = viewport.width;
      canvasElement.height = viewport.height;

      // 使用DOM canvas的上下文进行渲染
      const canvasContext = canvasElement.getContext("2d");
      const renderContext = {
        canvasContext: canvasContext,
        viewport: viewport,
      };

      await page.render(renderContext).promise;
    }
  }
};

const emits = defineEmits([]);
const props = defineProps({});
const state = reactive({});
onBeforeMount(() => {});
onMounted(() => {
  useRederPdf();
});
defineExpose({ state });
</script>
<style lang="scss" scoped>
.box-content {
  height: 100%;
  width: 100%;
}
</style>
